from typing import Any, Dict
from .Exporter import Exporter
import json
import os
import re

class JavascriptExporter(Exporter):
    def write_output(self, data: Dict[str, Dict[str, Any]], output_path: str, file_name: str):
        with open(output_path, 'w', encoding='utf-8') as f:
            if len(data.keys()) == 0:
                f.write('{}')
                return

            ret_str = ""
            for sheet_name, sheet_data in data.items():
                sheet_str = f"const {sheet_name}={{"
                if len(sheet_data.keys()) == 0:
                    sheet_str += "}"
                    ret_str += sheet_str + "\n"
                    continue

                sheet_str += "\n"
                for key, value in sheet_data.items():
                    sheet_str += f'{key}:{re.sub(r'"(\w+)":', r'\1:', json.dumps(value, ensure_ascii=False, separators=(",", ":")))},\n'

                sheet_str += "}"
                ret_str += sheet_str + "\n"
            
            # 将所有的表名使用 ， 拼接起来
            ret_str += f"export {{{",".join(data.keys())}}}"
            f.write(ret_str)

    def file_ext(self):
        return "js"